package com.flying;

import java.rmi.Naming;
import java.util.Arrays;




/**
 * @author 刘鹏飞
 * @Classname TestBinarySearch
 * @Date 2024/12/16 20:16
 * @Created by 刘鹏飞
 * @Description 测试二分查找
 */
public class TestBinarySearch {
    public static void main(String[] args) {


        int[ ] arr = { 30,20,50,10,80,9,7,12,100,40,8};

        int searchWord=20;

        // 二分查找前要对数组进行排序
        Arrays.sort(arr);

        System.out.println(Arrays.toString(arr));

        int index=binarySearch(arr,searchWord);
        // [7, 8, 9, 10, 12, 20, 30, 40, 50, 80, 100]
        System.out.println("index = " + index); // 5


    }

    static int binarySearch(int[] arr,int value){
        //
        int left=0;
        int right=arr.length-1;


        while(left<right){
            int middle=(left+right-1)/2;
            if (value<arr[middle]){
                right=middle-1;
            } else if (value>arr[middle]) {
                left=middle+1;
            }else {
                return middle;
            }
        }
        // 未找到,返回-1
        return -1;






    }
}
